package cn.tedu.ivos.base.security;

import cn.tedu.ivos.user.mapper.UserMapper;
import cn.tedu.ivos.user.pojo.vo.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.Set;

@Slf4j
@Service
public class CustomUserDetailsService implements UserDetailsService {
    @Autowired
    UserMapper userMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.debug("根据用户名查询用户详情",username);

        if (username==null){
            throw new UsernameNotFoundException("用户名不能为空");
        }
        UserVO userVO = userMapper.selectByUsername(username);
        if (userVO==null){
            throw new UsernameNotFoundException("用户名不存在");
        }
        CustomUserDetails userInfo = new CustomUserDetails();
        userInfo.setUsername(userVO.getUsername());
        userInfo.setPassword(userVO.getPassword());
        userInfo.setUserId(userVO.getId());

        Set<GrantedAuthority> authoritySet =new HashSet<>();
        GrantedAuthority authority = new SimpleGrantedAuthority("example");
        authoritySet.add(authority);
        userInfo.setAuthorities(authoritySet);
        return userInfo;
    }
}
